package com.itheima.web.request;

/**
 * @author Xiao
 * @date 2021/8/30
 */

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**java编码解码工具类
 * 	编码：java.net.URLEncoder.encode("需要被编码的内容","字符集(UTF-8)")
 * 	解码：java.net.URLDecoder.decode("需要被解码的内容","字符集(UTF-8)")
 */
public class URLDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        method2();
    }

    //乱码解决方案
    private static void method2() throws UnsupportedEncodingException {
        String username = "张三";
        String encode = URLEncoder.encode(username, "UTF-8");
        String decode = URLDecoder.decode(encode, "ISO-8859-1");
        byte[] bytes = decode.getBytes("ISO-8859-1");
        String s = new String(bytes, "UTF-8");
        System.out.println(encode); //%E5%BC%A0%E4%B8%89
        System.out.println(decode); //å¼ ä¸
        System.out.println(Arrays.toString(bytes)); //[-27, -68, -96, -28, -72, -119]
        System.out.println(s);  //张三
    }

    //乱码原因
    private static void method1() throws UnsupportedEncodingException {
        String encode = URLEncoder.encode("张三", "UTF-8");
        String decode1 = URLDecoder.decode(encode, "UTF-8");
        String decode2 = URLDecoder.decode(encode, "ISO-8859-1");
        System.out.println(encode); //%E5%BC%A0%E4%B8%89
        System.out.println(decode1); //张三
        System.out.println(decode2); //å¼ ä¸
    }
}
